package com.petrooil.core.dao;

import com.petrooil.core.model.WorkflowRule;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository("workflowRuleDao")
public class WorkflowRuleDaoImpl implements WorkflowRuleDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public WorkflowRule create(WorkflowRule workflowRule) {
        sessionFactory.getCurrentSession().persist(workflowRule);
        return workflowRule;
    }

    @Override
    public WorkflowRule get(Serializable id) {
        return (WorkflowRule) sessionFactory.getCurrentSession().get(WorkflowRule.class, id);
    }

    @Override
    public WorkflowRule update(WorkflowRule workflowRule) {
        sessionFactory.getCurrentSession().update(workflowRule);
        return workflowRule;
    }

    @Override
    public void delete(WorkflowRule workflowRule) {
        sessionFactory.getCurrentSession().delete(workflowRule);
    }

    @Override
    public WorkflowRule getRuleByFormAndDep(String form, String department) {
        return (WorkflowRule) sessionFactory.getCurrentSession().createQuery("from WorkflowRule where destinationDepartment=? AND form=?")
                .setParameter(0, department).setParameter(1, form).uniqueResult(); //TODO is not unique
    }

    @Override
    public List<WorkflowRule> getRulesByDepartment(String department) {
        return sessionFactory.getCurrentSession().createQuery("from WorkflowRule where destinationDepartment=?")
                .setParameter(0, department).list();
    }

    @Override
    public List<WorkflowRule> findAll() {
        return sessionFactory.getCurrentSession().createQuery("from WorkflowRule").list();
    }
}
